<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\BannersModel;
use app\model\RedisModel;
use app\model\UserCenterBannersModel;
use think\App;
use think\facade\Db;

class UserCenterBanners extends Base {

    protected $middleware = [Auth::class];
    private $userCenterBannerModel;

    public $cacheKey="u:banner:id:";

    private $req;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->userCenterBannerModel = new UserCenterBannersModel();

        $this->req = request()->param();

        $this->isLogin();
    }

    /*
     * 获取所有banner
     * */

    public function getList()
    {
        $list = $this->userCenterBannerModel->getList();

        $total = $this->userCenterBannerModel->getTotal();

        return $this->succData($total,$list);
    }



    /*
     * 新增banner
     * */
    public function add()
    {
        if(!isset($this->req['banners']) || empty($this->req['banners'])){
            return $this->fail("数据不能为空");
        }

        $banners=[];
        foreach ($this->req['banners'] as $key => $value){
            if(!isset($value['u_banner_pic']) || empty($value['u_banner_pic'])){
                return $this->fail("请上传图片");
            }
            if(!isset($value['u_banner_url']) || empty($value['u_banner_url'])){
                return $this->fail("请输入跳转链接");
            }
            $banner = [];
            $banner['u_banner_pic'] = $value['u_banner_pic'];
            $banner['u_banner_url'] = $value['u_banner_url'];
            $banner['u_banner_id'] = $key +1;
            $banners[] = $banner;
        }


        Db::startTrans();
        $where=[];
        $where[] = ['u_banner_status','=',1];
        $delRes = $this->userCenterBannerModel->delAll($where);
        $addres = $this->userCenterBannerModel->batchAdd($banners);
        if($delRes && $addres){
            $this->delAllCache();
            Db::commit();
            return $this->succ();
        }else{
            Db::rollback();
            return $this->fail();
        }
    }



    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }

}
